package elitech.vietnam.weatherfashion;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.dialog.MyProgressDialog;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.ImageUploader;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import eu.janmuller.android.simplecropimage.CropImage;

public class EditPostActivity extends Activity implements OnClickListener {

	private EditText textbox_content;
	private ImageView image_post;
	private Button button_save, mBtnBack;
	private ImageButton mButtonCrop;
	private TextView mTextHeader;

	String image_path;
	int postId, memId;
	String postContent;
	String path = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_edit_post);

		image_path = getIntent().getStringExtra("PostImage");
		postId = getIntent().getIntExtra("PostID", -1);
		memId = getIntent().getIntExtra("MemID", -1);
		postContent = getIntent().getStringExtra("PostContent");

		textbox_content = (EditText) findViewById(R.id.newpost_textbox_content);
		image_post = (ImageView) findViewById(R.id.newpost_image);
		button_save = (Button) findViewById(R.id.newpost_button_save);
		mButtonCrop = (ImageButton) findViewById(R.id.newpost_button_crop);
		mBtnBack = (Button) findViewById(R.id.newpost_button_back);
		//button_editpic = (Button) findViewById(R.id.editpost_button_editpic);
		mTextHeader = (TextView) findViewById(R.id.newpost_text_header);
		
		mTextHeader.setText(Html.fromHtml(getString(R.string.editstyle)));

		button_save.setOnClickListener(this);
		mButtonCrop.setOnClickListener(this);
		mBtnBack.setOnClickListener(this);

		UrlImageViewHelper.setUrlDrawable(image_post, Const.SERVER_IMAGE_URL + image_path);
		textbox_content.setText(postContent);
	}

	@Override
	public void onClick(View v) {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(textbox_content.getWindowToken(), 0);
		switch (v.getId()) {
		case R.id.newpost_button_save:
			if (postId > 0 && memId > 0) {
				new EditPostTask().execute();
			}
			break;
		case R.id.newpost_button_crop:
			new SaveThenOpenCropFile().execute(Const.SERVER_IMAGE_URL + image_path, NewPostActivity.CAM_PATH);
			break;
		case R.id.newpost_button_back:
			onBackPressed();
			break;
		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		int n = requestCode & 0xffff;
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;
		switch (n) {
//		case MainActivity.REQ_CODE_LIB:
//			path = Utils.getPath(data.getData(), this);
//			break;
//		case MainActivity.REQ_CODE_CAM:
//			path = NewPostActivity.CAM_PATH;
//			break;
		case NewPostActivity.CROP_FROM_CAMERA:
			path = data.getStringExtra(CropImage.IMAGE_PATH);
			break;
		default:
			break;
		}
		if (path == null || path.equals(""))
			Toast.makeText(this, getString(R.string.newpost_failed), Toast.LENGTH_LONG).show();
		else {
			image_post.setImageURI(Uri.fromFile(new File(path)));
//			MyProgressDialog dialog = new MyProgressDialog(this);
//			dialog.show();
//			if (ImageHelper.rotateImage(path, NewPostActivity.CAM_PATH))
//				path = NewPostActivity.CAM_PATH;
//			System.gc();
//			ImageHelper.displayThumbImage(image_post, path);
			image_path = "";
//			dialog.dismiss();
		}

	}

	class PicPickerDialog extends Dialog implements View.OnClickListener {

		public PicPickerDialog(Context context) {
			super(context, R.style.Dialog);
		}

		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.layout_dialogcamera);
			((Button) findViewById(R.id.dialogcamera_button_camera)).setOnClickListener(this);
			((Button) findViewById(R.id.dialogcamera_button_gallery)).setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			Intent intent = null;
			int req = 0;
			switch (v.getId()) {
			case R.id.dialogcamera_button_camera:
				intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(android.provider.MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
				intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(NewPostActivity.CAM_PATH)));
				req = MainActivity.REQ_CODE_CAM;
				break;

			case R.id.dialogcamera_button_gallery:
				intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				req = MainActivity.REQ_CODE_LIB;
				break;

			default:
				break;
			}

			if (intent != null)
				startActivityForResult(intent, req);
			dismiss();
		}
	}

	class EditPostTask extends AsyncTask<Integer, Integer, Boolean> {
		MyProgressDialog pDialog;

		@Override
		protected Boolean doInBackground(Integer... params) {
			boolean uploadOk = false;
			if (image_path.equals("")) {
				MemberDTO user = GlobalValue.getInstance(getApplicationContext()).readUserInfo();
				image_path = user.getId() + "_" + System.currentTimeMillis() + ".jpg";
				ImageUploader imageUploader = new ImageUploader();
				uploadOk = imageUploader.upload(path, image_path);
				if (!uploadOk)
					return false;
				image_path = "member_image/" + image_path;
			}
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			try {
				uploadOk = appService.updatePostMember(memId, postId, textbox_content.getText().toString(), image_path);
			} catch (IOException e) {
				uploadOk = false;
			}
			return uploadOk;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new MyProgressDialog(EditPostActivity.this);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected void onPostExecute(Boolean result) {
			super.onPostExecute(result);
			pDialog.dismiss();
			Intent intent = new Intent();
			if (result) {
				Toast.makeText(EditPostActivity.this, getString(R.string.newpost_success), Toast.LENGTH_SHORT).show();
				intent.putExtra("EditPostResult", true);
			} else {
				Toast.makeText(EditPostActivity.this, getString(R.string.newpost_failed), Toast.LENGTH_SHORT).show();
				intent.putExtra("EditPostResult", false);
			}
			setResult(Activity.RESULT_OK, intent);
			finish();
		}
	}
	
	@Override
	public void onBackPressed() {
		File file = new File(NewPostActivity.CAM_PATH);
		if (file.exists())
			file.delete();
		setResult(RESULT_CANCELED);
		super.onBackPressed();
	}
	
	
	class SaveThenOpenCropFile extends AsyncTask<String, Integer, Boolean> {
		MyProgressDialog mDialog;
		@Override
		protected Boolean doInBackground(String... params) {
			try {
				URL url = new URL(params[0]); //you can write here any link
                File file = new File(params[1]);

                /* Open a connection to that URL. */
                URLConnection ucon = url.openConnection();

                /*
                 * Define InputStreams to read from the URLConnection.
                 */
                InputStream is = ucon.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);

                /*
                 * Read bytes to the Buffer until there is nothing more to read(-1).
                 */
                ByteArrayBuffer baf = new ByteArrayBuffer(50);
                int current = 0;
                while ((current = bis.read()) != -1) {
                        baf.append((byte) current);
                }

                /* Convert the Bytes read to a String. */
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baf.toByteArray());
                fos.close();

            } catch(IOException e) {
            	return false;
            }
			path = params[1];
			image_path = "";
			return true;
		}
		@Override
		protected void onPreExecute() {
			mDialog = new MyProgressDialog(EditPostActivity.this);
			mDialog.show();
		}
		@Override
		protected void onPostExecute(Boolean result) {
			mDialog.dismiss();
			if (!result) {
				Toast.makeText(EditPostActivity.this, "An error has occurred. Please try again.", Toast.LENGTH_SHORT).show();
				return;
			}
			Intent intent = new Intent(EditPostActivity.this, CropImage.class);
			intent.putExtra(CropImage.IMAGE_PATH, path);
			intent.putExtra(CropImage.SCALE, true);
			intent.putExtra(CropImage.ASPECT_X, 0);
			intent.putExtra(CropImage.ASPECT_Y, 0);
			startActivityForResult(intent, NewPostActivity.CROP_FROM_CAMERA);
		}
	}
}
